import {useEffect, useState} from "react";

const useScrollPosition = () => {
  const [scrollX, setScrollX] = useState(0);
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollX(window.scrollX);
      setScrollY(window.scrollY);
    }

    //监听: useEffect没有依赖值, 仅在组件第一次渲染时执行
    window.addEventListener("scroll", handleScroll);

    return () => {
      //取消监听: useEffect没有依赖值, 仅在组件被卸载时执行
      window.removeEventListener("scroll", handleScroll);
    }
  }, []);

  return [scrollX, scrollY]
}

export default useScrollPosition;